#include "land_graphics.h"

#define LAND_2D_CORE

#include "init.h"

static void
onEvent(LandObj* obj, LandObjEvent* evt) {
	LandButton* btn = (LandButton*)obj;
	if (evt->type != LAND_OBJ_WINDOW_EVENT) {
		return;
	}
	LandWindowEvent* we = evt->ud;
	switch (we->type) {
	case LAND_WINDOW_EVENT_MOUSE_MOVE: {
		if (!btn->onStatus) { return; }
		if (btn->status == LAND_BUTTON_STATUS_DOWN) {
			return;
		}
		int hit = landObjHit(obj,
			(LandFloat)we->mouse.x, (LandFloat)we->mouse.y);
		int status = hit ? LAND_BUTTON_STATUS_HOVER : LAND_BUTTON_STATUS_UP;
		if (btn->status == status) {
			return;
		}
		btn->status = status;
		btn->onStatus(btn, evt);
		break;
	}
	case LAND_WINDOW_EVENT_MOUSE_DOWN: {
		if (!btn->onStatus) { return; }
		if (btn->status == LAND_BUTTON_STATUS_DOWN) {
			return;
		}
		int hit = landObjHit(obj,
			(LandFloat)we->mouse.x, (LandFloat)we->mouse.y);
		if (!hit) { return; }
		evt->intercept = 1;
		btn->status = LAND_BUTTON_STATUS_DOWN;
		btn->onStatus(btn, evt);
		break;
	}
	case LAND_WINDOW_EVENT_MOUSE_UP: {
		if (btn->status == LAND_BUTTON_STATUS_UP) {
			return;
		}
		int hit = landObjHit(obj,
			(LandFloat)we->mouse.x, (LandFloat)we->mouse.y);
		if (hit) {
			if (btn->status == LAND_BUTTON_STATUS_DOWN) {
				if (btn->onClick) {
					btn->onClick(btn, evt);
				}
			}
			btn->status = LAND_BUTTON_STATUS_HOVER;
		}
		else {
			btn->status = LAND_BUTTON_STATUS_UP;
		}
		if (btn->onStatus) {
			btn->onStatus(btn, evt);
		}
	}
	default:
		return;
	}
}


LAND_2D_API LandButton*
landNewButton() {
	return landNewExtendButton(sizeof(LandButton), NULL);
}

LAND_2D_API LandButton*
landNewExtendButton(size_t size, LandRefFree free) {
	LandButton* btn = landNewExtendObj(sizeof(LandButton), free);
	btn->obj.onEvent = onEvent;
	return btn;
}

